package com.bingxue.edu.common.job;

import com.bingxue.edu.common.enums.ClassStatusEnum;
import com.bingxue.edu.framework.job.DynamicJob;
import com.bingxue.edu.management.education.service.ClassInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDate;
import java.util.List;

import static com.bingxue.edu.management.education.model.entity.table.ArrangeTemplateTableDef.ARRANGE_TEMPLATE;
import static com.bingxue.edu.management.education.model.entity.table.ClassInfoTableDef.CLASS_INFO;

/**
 * @author panbo
 * @since 2024/12/23
 */
@Slf4j
@DisallowConcurrentExecution
@RequiredArgsConstructor
@DynamicJob(name="班级状态更新任务", cron = "0 0 6 * * ? ")
public class ClassStatusUpdateJob extends QuartzJobBean {

    private final ClassInfoService classInfoService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        log.info("班级状态更新任务开始");
        // 未开课 -> 开课
        List<String> ids1 = classInfoService.queryChain()
                .select(CLASS_INFO.ID)
                .leftJoin(ARRANGE_TEMPLATE).on(ARRANGE_TEMPLATE.ID.eq(CLASS_INFO.ARRANGE_TEMPLATE_ID))
                .where(CLASS_INFO.CLASS_STATUS.eq(ClassStatusEnum.WAITING))
                .and(ARRANGE_TEMPLATE.START_DATE.le(LocalDate.now()))
                .and(ARRANGE_TEMPLATE.END_DATE.gt(LocalDate.now()))
                .listAs(String.class);
        if (!ids1.isEmpty()) {
            classInfoService.updateChain()
                    .where(CLASS_INFO.ID.in(ids1))
                    .set(CLASS_INFO.CLASS_STATUS, ClassStatusEnum.TEACHING)
                    .update();
        }
        // 开课 -> 结课
        List<String> ids2 = classInfoService.queryChain()
                .select(CLASS_INFO.ID)
                .leftJoin(ARRANGE_TEMPLATE).on(ARRANGE_TEMPLATE.ID.eq(CLASS_INFO.ARRANGE_TEMPLATE_ID))
                .where(CLASS_INFO.CLASS_STATUS.eq(ClassStatusEnum.TEACHING))
                .and(ARRANGE_TEMPLATE.END_DATE.lt(LocalDate.now()))
                .listAs(String.class);
        if (!ids2.isEmpty()) {
            classInfoService.updateChain()
                    .where(CLASS_INFO.ID.in(ids2))
                    .set(CLASS_INFO.CLASS_STATUS, ClassStatusEnum.COMPLETED)
                    .update();
        }

//        classStatService.computePerformanceRate();
        log.info("班级状态更新任务结束");
    }
}
